import {
  LockOutlined,
  UserOutlined,
  LoginOutlined,
  ArrowRightOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import { Alert, message, Tabs, Row, Col, Button, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import {
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormDependency,
  ProFormText,
  LoginForm,
  ProFormTreeSelect,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Link, history, FormattedMessage, useModel } from '@umijs/max';
import { fakeAccountLogin, saveForRegister } from '@/services/login';
import styles from './index.less';
import AES from 'crypto-js/aes';
import ECB from 'crypto-js/mode-ecb';
import Pkcs7 from 'crypto-js/pad-pkcs7';
import Utf8 from 'crypto-js/enc-utf8';
import moment from 'moment';
import Footer from '@/components/Footer';
import {
  factorySelectRegister,
  storeselectionBoxAll,
  productionLineSelectByShops,
  sectionSelectByShops,
  allUserSelect,
  departmentTree,
  roleSelectRegister,
} from '@/services/system';
import { doFetch } from '@/utils/doFetch';
import { ProDescriptions } from '@ant-design/pro-components';
import defaultSettings from '../../../../config/defaultSettings';

const { Search } = Input;

let col = { xs: 0, sm: 0, md: 7, lg: 6, xl: 6, xxl: 6 },
  cols = { xs: 24, sm: 24, md: 17, lg: 18, xl: 18, xxl: 18 },
  coles = { xs: 12, sm: 12, md: 12, lg: 8, xl: 8, xxl: 8 };

const Login = () => {
  const formRef = useRef();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tabkey, settabkey] = useState('1');
  const [visible, setvisible] = useState(false);
  const [data, setdata] = useState();
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo(),
      menuData = await initialState?.getmenuData();

    if (userInfo) {
      await setInitialState((s) => {
        return { ...s, currentUser: userInfo?.data, newMenu: menuData };
      });
    }
  };

  //登录
  const handleLogin = async (values) => {
    let timestamp = moment().valueOf().toString() + 'acb';
    let newtimestamp = AES.encrypt(timestamp, Utf8.parse('NANGAODEAESKEY--'), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    let password = AES.encrypt(values.password, Utf8.parse(timestamp), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    const postdata = {
      accountName: values.userName,
      password: password,
      encryptKey: newtimestamp,
    };
    try {
      // 登录
      const res = await fakeAccountLogin({ ...postdata });
      if (res.code === '0000') {
        let token = res?.data?.token;
        localStorage.setItem('TOKENES', token);
        await fetchUserInfo();
        message.success('🎉 🎉 🎉  登录成功！');
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        history.push('/');
        return;
      }
    } catch (error) {}
  };

  const handleReg = async (values) => {
    // 登录
    const res = await saveForRegister({ ...values });
    if (res.code === '0000') {
      message.success('注册成功,根据用户名可查询注册进度');
      formRef.current.resetFields();
      return;
    }
  };

  const handleSubmit = async (values) => {
    if (tabkey == '1') {
      await handleLogin(values);
    } else {
      await handleReg(values);
    }
  };

  return (
    <Row className={styles.container}>
      <Col {...col}>
        <div
          className="img"
          style={{
            backgroundImage: `url(${require('@/assets/loginbg.jpg')})`,
            position: 'relative',
          }}
        >
          <div className="cover">
            <img alt="logo" src={'./logo.png'} />
          </div>
          <Drawer visible={visible} placement="left" style={{ maxWidth: '100vw' }}>
            <div className={styles.search}>
              <h2
                style={{
                  fontSize: 16,
                  borderBottom: '6px solid #eee',
                  marginBottom: 12,
                  paddingBottom: 12,
                }}
                className="spread"
              >
                <a>查询注册进度</a>
                <CloseOutlined
                  style={{ color: 'red' }}
                  onClick={() => {
                    setvisible(false);
                  }}
                />
              </h2>
              <Search
                placeholder="请输入用户名"
                allowClear
                onSearch={(value) => {
                  if (value) {
                    doFetch({
                      url: '/ngic-auth/sysAccountApply/queryByAccount',
                      params: { accountName: value.replace(/^\s+|\s+$/g, '') },
                    }).then((res) => {
                      if (res.code == '0000') {
                        let data = res?.data?.data;
                        setdata(data);
                      }
                    });
                  }
                }}
                style={{ width: '100%', marginBottom: 15 }}
              />

              <ProDescriptions
                columns={[
                  {
                    title: '用户名',
                    dataIndex: 'accountName',
                    key: 'accountName',
                  },
                  {
                    title: '姓名',
                    dataIndex: 'userName',
                    key: 'userName',
                  },
                  {
                    title: '联系电话',
                    dataIndex: 'telephone',
                    key: 'telephone',
                  },
                  {
                    title: '工厂',
                    dataIndex: 'factoryName',
                    key: 'factoryName',
                  },
                  {
                    title: '组织',
                    dataIndex: 'departmentName',
                    key: 'departmentName',
                  },
                  {
                    title: '负责仓库',
                    dataIndex: 'chargeStoreName',
                    key: 'chargeStoreName',
                  },
                  {
                    title: '角色',
                    dataIndex: 'roleName',
                    key: 'roleName',
                  },
                  {
                    title: '直属领导',
                    dataIndex: 'parentName',
                    key: 'parentName',
                  },
                  {
                    title: '邮箱',
                    dataIndex: 'mailNo',
                    key: 'mailNo',
                  },
                  {
                    title: '审批结果',
                    dataIndex: 'auditResultName',
                    key: 'auditResultName',
                  },
                  {
                    title: '审批意见',
                    dataIndex: 'auditOpinion',
                    key: 'auditOpinion',
                  },
                  {
                    title: '审批状态',
                    dataIndex: 'statusName',
                    key: 'statusName',
                  },
                  {
                    title: '备注',
                    dataIndex: 'remark',
                    key: 'remark',
                  },
                  {
                    title: '申请时间',
                    dataIndex: 'applyTime',
                    key: 'applyTime',
                  },
                  {
                    title: '审批时间',
                    dataIndex: 'auditTime',
                    key: 'auditTime',
                  },
                  {
                    title: '审批人',
                    dataIndex: 'auditUserName',
                    key: 'auditUserName',
                  },
                ]}
                column={1}
                dataSource={data}
              />
            </div>
          </Drawer>
        </div>
      </Col>
      <Col
        {...cols}
        onClick={() => {
          setvisible(false);
        }}
      >
        <div className="logincontent">
          <div className={styles.content}>
            <LoginForm
              submitter={{
                render: (props) => {
                  return (
                    <Button
                      {...props}
                      style={{ width: '100%' }}
                      type="primary"
                      size="large"
                      icon={tabkey === '1' ? <LoginOutlined /> : <ArrowRightOutlined />}
                      onClick={async () => {
                        let values = await formRef.current.validateFields();
                        await handleSubmit(values);
                      }}
                    >
                      {tabkey === '1' ? '登录' : '注册'}
                    </Button>
                  );
                },
              }}
              onValuesChange={async (values) => {
                if (Object.keys(values)[0] == 'factoryIdList') {
                  formRef.current.setFieldsValue({ storeIdList: [] });
                }
              }}
              title={<span style={{ color: '#fff' }}>{defaultSettings.name}</span>}
              subTitle={<span style={{ color: 'rgba(255,255,255,0.6)' }}>智慧仓储管理系统</span>}
              initialValues={{
                autoLogin: true,
              }}
              onFinish={async (values) => {
                await handleSubmit(values);
              }}
              style={{
                width: tabkey === '1' ? 328 : '100%',
              }} //样式适配
              formRef={formRef}
            >
              <Tabs
                activeKey={tabkey}
                onChange={settabkey}
                tabBarExtraContent={
                  <a
                    style={{ color: 'rgba(255,255,255,0.6)' }}
                    onClick={(e) => {
                      e.stopPropagation();
                      setvisible(true);
                    }}
                  >
                    查询注册进度
                  </a>
                }
                items={[
                  {
                    label: '登录',
                    key: '1',
                    children: tabkey == '1' && (
                      <>
                        <ProFormText
                          name="userName"
                          fieldProps={{
                            size: 'large',
                            prefix: <UserOutlined className={styles.prefixIcon} />,
                          }}
                          placeholder="用户名"
                          rules={[
                            {
                              required: true,
                              message: '请输入用户名!',
                            },
                          ]}
                        />
                        <ProFormText.Password
                          name="password"
                          fieldProps={{
                            size: 'large',
                            prefix: <LockOutlined className={styles.prefixIcon} />,
                          }}
                          placeholder="密码"
                          rules={[
                            {
                              required: true,
                              message: '请输入密码！',
                            },
                          ]}
                        />
                      </>
                    ),
                  },
                  {
                    label: '注册',
                    key: '2',
                    children: tabkey == '2' && (
                      <Row className="reg" gutter={12}>
                        <Col {...coles}>
                          <ProFormText
                            fieldProps={{
                              style: {
                                height: 32,
                              },
                            }}
                            name="accountName"
                            label={<b>用户名</b>}
                            placeholder="请输入用户名"
                            rules={[
                              {
                                required: true,
                                message: '请输入用户名!',
                              },
                            ]}
                          />
                        </Col>

                        <Col {...coles}>
                          <ProFormText
                            fieldProps={{
                              style: {
                                height: 32,
                              },
                            }}
                            name="userName"
                            label={<b>姓名</b>}
                            placeholder="请输入姓名"
                            rules={[
                              {
                                required: true,
                                message: '请输入姓名!',
                              },
                            ]}
                          />
                        </Col>

                        <Col {...coles}>
                          <ProFormText
                            fieldProps={{
                              style: {
                                height: 32,
                              },
                            }}
                            name="telephone"
                            label={<b>联系电话</b>}
                            placeholder="请输入联系电话"
                            rules={[
                              {
                                required: false,
                                message: '请输入联系电话!',
                              },
                              {
                                pattern: /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/,
                                message: '手机号格式错误！',
                              },
                            ]}
                          />
                        </Col>

                        <Col {...coles}>
                          <ProFormTreeSelect
                            name="departmentId"
                            label={<b>组织</b>}
                            placeholder="请选择组织"
                            fieldProps={{
                              fieldNames: {
                                label: 'title',
                                value: 'key',
                                children: 'children',
                              },
                              allowClear: true,
                            }}
                            request={async () => {
                              let res = await departmentTree({});
                              return res?.data?.dataList ?? [];
                            }}
                            rules={[
                              {
                                required: true,
                                message: '请选择组织!',
                              },
                            ]}
                          />
                        </Col>

                        <Col {...coles}>
                          <ProFormSelect
                            fieldProps={{
                              mode: 'multiple',
                              maxTagCount: 1,
                            }}
                            name="factoryIdList"
                            label={<b>工厂</b>}
                            placeholder="请选择工厂"
                            request={async () => {
                              let res = await factorySelectRegister({});
                              return res?.data?.dataList ?? [];
                            }}
                            rules={[
                              {
                                required: true,
                                message: '请选择工厂!',
                              },
                            ]}
                          />
                        </Col>
                        <Col {...coles}>
                          <ProFormDependency name={['factoryIdList']}>
                            {({ factoryIdList }) => {
                              return (
                                <ProFormSelect
                                  fieldProps={{
                                    mode: 'multiple',
                                    maxTagCount: 1,
                                  }}
                                  name="storeIdList"
                                  label={<b>负责仓库</b>}
                                  placeholder={'请选择负责仓库'}
                                  params={{ factoryIdList }}
                                  request={async (params) => {
                                    let res = await storeselectionBoxAll(params);
                                    return res?.data?.dataList ?? [];
                                  }}
                                  rules={[
                                    {
                                      required: false,
                                      message: '请选择负责仓库!',
                                    },
                                  ]}
                                />
                              );
                            }}
                          </ProFormDependency>
                        </Col>

                        <Col {...coles}>
                          <ProFormSelect
                            fieldProps={{
                              mode: 'multiple',
                              maxTagCount: 1,
                            }}
                            name="roleIdList"
                            label={<b>角色配置</b>}
                            placeholder="请选择角色配置"
                            request={async () => {
                              let res = await roleSelectRegister({});
                              return res?.data?.dataList ?? [];
                            }}
                            rules={[
                              {
                                required: false,
                                message: '请选择角色配置!',
                              },
                            ]}
                          />
                        </Col>

                        <Col {...coles}>
                          <ProFormSelect
                            name="parentId"
                            fieldProps={{
                              showSearch: true,
                            }}
                            label={<b>直属领导</b>}
                            placeholder="请选择直属领导"
                            request={async () => {
                              let res = await allUserSelect({});
                              return res?.data?.dataList ?? [];
                            }}
                            rules={[
                              {
                                required: false,
                                message: '请选择直属领导!',
                              },
                            ]}
                          />
                        </Col>
                        <Col {...coles}>
                          <ProFormText
                            fieldProps={{
                              style: {
                                height: 32,
                              },
                            }}
                            name="mailNo"
                            label={<b>邮箱</b>}
                            placeholder="请输入邮箱"
                            rules={[
                              {
                                required: false,
                                message: '请输入邮箱!',
                              },
                            ]}
                          />
                        </Col>
                        <Col span={24}>
                          <ProFormTextArea
                            name="remark"
                            label={<b>备注</b>}
                            placeholder="请输入备注"
                            request={async () => {
                              let res = await allUserSelect({});
                              return res?.data?.dataList ?? [];
                            }}
                            rules={[
                              {
                                required: false,
                                message: '请输入备注!',
                              },
                            ]}
                          />
                        </Col>
                      </Row>
                    ),
                  },
                ]}
              />
            </LoginForm>
          </div>
          <Footer />
        </div>
      </Col>
    </Row>
  );
};

export default Login;
